<template>
  <div style="width:100%; height:100%; position:relative;">
    <el-form ref="cameraAiFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="form.eventType" placeholder="请选择">
          <el-option v-for="dict in event_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事件说明" prop="eventDesc">
        <el-input v-model="form.eventDesc" type="textarea" :autosize="{ minRows: 2 }" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <div style="width: 600px;display: flex">
          <el-input v-model="form.equipmentName" placeholder="请选择设备" style="width: 300px; margin-right: 10px; pointer-events: none;"/>
          <el-button type="primary" plain @click="openSelectDevice">选择</el-button>
        </div>
      </el-form-item>
      <el-form-item label="事件地点" prop="eventAddress">
        <el-input v-model="form.eventAddress" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="事件等级" prop="eventGrade">
        <el-select v-model="form.eventGrade" placeholder="请选择">
          <el-option v-for="dict in event_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="抓拍图片">
        <div class="image-list">
          <template v-for="(image,index) in imageList">
            <div style="position: relative; display: block; height: 100px; width: 100px; margin-left: 5px; margin-bottom: 5px; border: 1px solid #ccc; padding: 2px;">
              <el-icon style="position: absolute; top: 2px; right: 2px; cursor: pointer; z-index: 1000;" @click="removeImage(index)" ><Close /></el-icon>
              <el-image :src="image.filePath" fit="contain" class="image-item" style="height: 100%;"/>
            </div>
          </template>
          <el-button class="upload-btn" @click="showSelectImage=true">上传</el-button>
        </div>
      </el-form-item>
    </el-form>

    <div class="footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="emit('close')" >取 消</el-button>
    </div>

    <!-- 选择图片 -->
    <el-dialog v-model="showSelectImage" title="选择图片" width="1300" append-to-body destroy-on-close>
      <select-image :equipment-id="props.equipmentId" :image-list="imageList" @submit="addImage" @close="showSelectImage=false" />
    </el-dialog>

    <!-- 选择设备弹框-->
    <DeviceSelect ref="deviceSelectRef" :data="form.equipmentId" :data-source="2" :disable-check="false" :multiple="false" @confirm-call-back="selectDevice"></DeviceSelect>
  </div>

</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import SelectImage from '@/views/security/video-monitor/real-time-monitor/components/SelectImage.vue';
import request from '@/utils/request';
import DeviceSelect from '@/components/DeviceSelect/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { event_type, alarm_grade, event_grade } = toRefs<any>(proxy?.useDict('event_type', 'alarm_grade', 'event_grade'));
const props = defineProps({
  equipmentId: {
    type: String,
    default: null
  },
  equipmentName: {
    type: String,
    default: null
  },
  url: propTypes.string.def(''),
  businessId: {
    type: String,
    default: null
  },
  businessType: {
    type: String,
    default: null
  },
  eventSource: {
    type: Number,
    default: null,
    required: true
  }
});
const emit = defineEmits(['close', 'submit']);

const buttonLoading = ref(false);
const cameraAiFormRef = ref<ElFormInstance>();
const showSelectImage = ref(false);
const imageList = ref([]);

const data = reactive({
  rules: {
    eventType: [
      { required: true, message: '请选择', trigger: 'change' }
    ],
    equipmentName: [
      { required: true, message: '请选择', trigger: 'change' }
    ],
    eventAddress: [
      { required: true, message: '请输入', trigger: 'blur' }
    ],
    eventGrade: [
      { required: true, message: '请选择', trigger: 'change' }
    ]
  }
});

const { rules } = toRefs(data);

const form = ref<any>({
  eventType: undefined,
  eventAddress: undefined,
  eventGrade: undefined,
  eventSource: undefined,
  equipmentId: props.equipmentId,
  equipmentName: props.equipmentName,
  imageIdList: undefined,
  businessId: undefined,
  businessType: undefined
})

const addImage = (fileList, equipmentId)=> {
  imageList.value = imageList.value.concat(fileList)
  form.value.equipmentId = equipmentId
}

/** 提交按钮 */
const submitForm = () => {
  cameraAiFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (imageList.value) { form.value.imageIdList = imageList.value.map(item => item.fileId); }
      if (props.equipmentId) { form.value.equipmentId = props.equipmentId }
      form.value.businessId = props.businessId
      form.value.businessType = props.businessType
      form.value.eventSource = props.eventSource // 事件来源（1：物联设备；2：安防巡视；3：设备巡检；4：业主上报；）
      if (!props.eventSource) {
        form.value.eventSource = 4
      } else {
        form.value.eventSource = props.eventSource
      }
      buttonLoading.value = true;
      request({
        url: '/event/eventRecord',
        method: 'post',
        data: form.value
      }).then((res) => {
        if (res.code == 200) {
          proxy?.$modal.msgSuccess('提交成功');
          emit('submit')
          emit('close')
        } else {
          proxy?.$modal.msgError(res.msg);
        }
      }).finally(() => buttonLoading.value = false)
    }
  });
}
const deviceSelectRef = ref<any>();
const openSelectDevice = () => {
  form.value.equipmentId = props.equipmentId
  deviceSelectRef.value.open();
}
/**
 * 选择设备
 */
const selectDevice = (data: any[]) => {
  console.log('选择设备：', data)

  let device = data.length !== 0 ? data[0] : undefined;
  form.value.equipmentId = device.equipmentId; // 更新设备 ID
  form.value.equipmentName = device.equipmentName; // 更新设备名称
};
/**
 * 删除图片
 */
const removeImage = (index) =>{
  imageList.value.splice(index, 1)
}

onMounted(()=> {

})
onBeforeUnmount(()=>{

})

</script>

<style lang="scss" scoped>
  .footer {
    display: flex;
    justify-content: center;
  }
  .upload-btn {
    height: 100px !important;
    width: 100px;
    border-style: dashed;
    margin-left: 5px
  }
  .image-list {
    display: flex;
    flex-wrap: wrap;
  }

</style>
